#!/usr/bin/python
import re
import sys
import os
import subprocess
import json

from generateHTML import *
from parseTaskFiles import *
from sqlite3task import *


def main():
    sys.argv[0] = "task"
    #Run original taskwarrior
    subprocess.call(sys.argv)


    #Get data location
    location = ""
    output = subprocess.check_output(['task', 'show', 'data.location'])
    for line in output.split("\n"):
        if re.match(r'^data\.location', line):
            location = re.sub(r'^data\.location', "", line).strip()
            break
    if location == "":
        sys.stderr.write("Creating html files failed. (data.location not found)")
        return

    #Read the JSON data
    pending = readJSONfile(location + "/pending.data", True)
    completed = readJSONfile(location + "/completed.data")

    #generate the HTML Files
    generateTaskListFull(pending, completed, "/tmp/list.htm")

    return

    if os.path.exists("/tmp/test.db"):
        os.unlink("/tmp/test.db")
    createDB("/tmp/test.db")
    insertTasks("/tmp/test.db", [{ "uuid":"qwety", "newOne":"n33", "newTwo":"1" }] )
    insertTasks("/tmp/test.db", [{ "uuid":"qwety1", "newOne":"235", "ntwTwo":"2" }] )
    insertTasks("/tmp/test.db", [{ "uuid":"qwety2", "newzne":"23", "newTwo":"3" }] )
    insertTasks("/tmp/test.db", [{ "uuid":"qwety3", "newxne":"2", "newgwo":"4" }] )
    #print getTasks("/tmp/test.db")

    insertHistory("/tmp/test.db", readUndoFile(location + "/undo.data"))

    #print extractHistory("/tmp/test.db")

    new = { "uuid":"1206c144-13fb-46a2-bd9e-fc36da3118dd", "newtag":"new"}
    old = { "uuid":"1206c144-13fb-46a2-bd9e-fc36da3118dd", "oldtag":"old"}

    processHistory("/tmp/test.db", [ { "time":"12345", "old":old, "new":new }])

    new = { "uuid":"8206c144-13fb-46a2-bd9e-fc36da3118dd", "newtag":"uid"}

    processHistory("/tmp/test.db", [ { "time":"12345", "new":new }])
    

if __name__ == "__main__":
    main()
